
var vm = new Vue({
    el: "#carVue",
    data: {
        loading: true,
        buy_car:[],                 //购物车信息
        product:[],                 //商品实时信息
        product_name:'',            //商品名字
        product_name_english:'',    //商品名字
        product_image:'',           //商品图片
        del_id:'',                  //删除的商品id
        collect_message:'',
        collect_message_english:'',
        user_id:'',
        web_token:'',
        supplier_id:'',
        pageNo: 1,
        info:[],
        oss_url:oss_url,
        nodata:''
    },
    methods: {
        settlement:function () {
            if (!this.user_id ){
                location.href = "/userweb/index/login.html";
            }
            validToken(); //验证tonken.
            var arr = '', flag = 0;
            var ids = [];
            $(".cartBox input[name='ids']:checkbox").each(function (i, v) {
                if (true == $(v).prop("checked")) {
                    //arr.push($(this).val());
                    arr += $(this).val()+',';
                    flag++;
                }
            });
            if (flag === 0) {
                layer.msg("请选择要购买的商品！",{
                    skin:'winning-class',
                    time:3000
                });
                return false;
            }
            arr = arr.substring(0,arr.length-1);
            ids = arr.split(',');
            var goods = this.buy_car;
            for (var i=0;i<goods.length;i++){
                if (goods[i]['is_open']!=1){
                    layer.msg(goods[i]['supplier_name']+',暂停营业!',{
                        skin:'winning-class',
                        time:3000
                    });
                    return false;
                }
                var total_money = 0;
                for (var k=0;k<goods[i]['product'].length;k++){
                    for (var ii=0;ii<ids.length;ii++){
                        if (goods[i]['product'][k]['cart_id'] == ids[ii]){
                            if (goods[i]['product'][k]['is_shelves']!=1){
                                layer.msg(goods[i]['product'][k]['product_name']+',已下架!',{
                                    skin:'winning-class',
                                    time:3000
                                });
                                return false;
                            }
                            if (goods[i]['product'][k]['num']>goods[i]['product'][k]['stock']){
                                layer.msg(goods[i]['product'][k]['product_name']+',库存不足!',{
                                    skin:'winning-class',
                                    time:3000
                                });
                                return false;
                            }
                            if(goods[i]['product'][k]['num']==0){
                                layer.msg(goods[i]['product'][k]['product_name']+',暂无库存!',{
                                    skin:'winning-class',
                                    time:3000
                                });
                                return false;
                            }
                            var money = goods[i]['product'][k]['total_price'];
                            total_money += parseFloat(money);
                        }
                    }
                }
                // if (total_money<goods[i]['minimum']){
                //     layer.msg(goods[i]['supplier_name']+',最低消费 ￡'+goods[i]['minimum'],{
                //         skin:'winning-class',
                //         time:3000
                //     });
                //     return false;
                // }
            }
            //更改数据库对应的数量.
            var url = '/userweb/Homepage/changCartNum';
            var data = {
                user_id:  this.user_id,
                goods:    goods
            };
            this.$http.post(url, data, {
                emulateJSON: true
            }).then(function (res) {
                /* if (res.data.status == 200) {
                     this.buy_car = res.data.buy_car;
                 }*/
            }, function (res) {
            });
            location.href = '/userweb/index/orderNow.html?ids='+arr+'&type=1';
        },
        productNum:function (index,product,list) {
            if (isNaN(product.num)){
                layer.msg('请输入数字</br>Please enter a number',{
                    skin:'winning-class',
                    time:3000
                });
                product.num = 1;
            }
            if (list.is_open!=1){
                layer.msg(list.supplier_name+',暂停营业!',{
                    skin:'winning-class',
                    time:3000
                });
                return false;
            }
            if (index == 2){  //增加
                product.num = parseInt(product.num);
                product.num += 1;
            }
            if (index == 1){ //减少
                product.num = parseInt(product.num);
                product.num -= 1;
            }
            if (product.num<1 || !product.num){
                product.num = 1;
            }
            if (product.num > product.stock){
                product.num = product.stock;
                layer.msg(product.product_name+',库存不足!',{
                    skin:'winning-class',
                    time:3000
                });
            }
            if (product.num <= product.stock){
                var total_price = parseFloat(product.price) * parseFloat(product.num);
                var total_tax   = parseFloat(product.tax)   * parseFloat(product.num);
                product.total_tax      = (total_tax).toFixed(2);
                product.total_price    = (parseFloat(total_tax) + parseFloat(total_price)).toFixed(2);
               /* localStorage.removeItem('buy_car');
                $.each(this.buy_car,function (i,v) {
                    buy_car_add([v][0]);
                });*/
            }
            setTimeout(function () {
                totalMoney();
            },50);
        },
        del:function () {
            if (!this.user_id ){
                location.href = "/userweb/index/login.html";
            }
            validToken(); //验证tonken.
            var url = '/userweb/Homepage/delCart';
            var data = {
                user_id:  this.user_id,
                delStr:   this.del_id
            };
            // console.log(data);return false;
            this.$http.post(url, data, {
                emulateJSON: true
            }).then(function (res) {
                /*var _this = this;
                setTimeout(function () {
                    _this.loading = false;
                }, 300);*/
                this.loading = false;
            }, function (res) {
            });
           /* var _this = this;
            $.each(_this.buy_car,function (i,v) {
                $.each(_this.buy_car[i]['product'],function (ii,vv) {
                    if (_this.del_id == _this.buy_car[i]['product'][ii]['cart_id']){
                        _this.buy_car[i]['product'].splice([ii][0],1);
                        return false;
                    }
                });
                if (_this.buy_car[i]['product'].length == 0){
                    _this.buy_car.splice([i][0],1);
                    return false;
                }
            });
            localStorage.removeItem('buy_car');
            $.each(_this.buy_car,function (i,v) {
                buy_car_add([v][0]);
            });
            _this.req();*/
            this.req();
        },
        jump:function (product) {
            this.del_id                     = product.cart_id;
            this.product_name               = product.product_name;
            this.product_image              = this.oss_url + product.product_image;
        },
        collection:function (product) {
            if (!this.user_id ){
                location.href = "/userweb/index/login.html";
            }
            this.del_id = product.cart_id;
            validToken(); //验证tonken.
            var url = '/api/Collection/confirmCollectProduct';
            var data = {
                user_id:     this.user_id,
                product_id:  product.product_id,
                web_token:   this.web_token,
                type:'WEB'
            };
            this.$http.post(url, data, {
                emulateJSON: true
            }).then(function (res) {
                this.product_name               = product.product_name;
                this.product_image              = oss_url + product.product_image;
                if (res.data.status == 200){
                    this.collect_message            = '收藏成功，您可以在收藏夹中查看该商品';
                    this.collect_message_english    = 'Collection success, you can view this product in the favorites';
                    this.del();
                   /* for (var i=0;i<this.buy_car.length;i++){
                        for (var k=0;k<this.buy_car[i]['product'].length;k++){
                            if (product.cart_id == this.buy_car[i]['product'][k]['cart_id']){
                                this.buy_car[i]['product'].splice([k][0],1);
                                continue;
                            }
                        }
                        if (this.buy_car[i]['product'].length == 0){
                            this.buy_car.splice([i][0],1);
                            continue;
                        }
                    }
                    localStorage.removeItem('buy_car');
                    $.each(this.buy_car,function (i,v) {
                        buy_car_add([v][0]);
                    });*/
                }else {
                    this.collect_message            = '已收藏过该商品';
                    this.collect_message_english    = 'Collection this product';
                }
            }, function (res) {
            });
        },
        req:function () {
            this.loading = true;
            var url = '/userweb/Homepage/contrast';
            var data = {
                user_id:  this.user_id
            };
            this.$http.post(url, data, {
                emulateJSON: true
            }).then(function (res) {
                if (res.data.status == 200) {
                    this.buy_car = res.data.buy_car;
                    setTimeout(function () {
                        //全局的checkbox选中和未选中的样式
                        var $allCheckbox = $('input[type="checkbox"]'),     //全局的全部checkbox
                            $wholeChexbox = $('.whole_check'),
                            $cartBox = $('.cartBox'),                       //每个商铺盒子
                            $shopCheckbox = $('.shopChoice'),               //每个商铺的checkbox
                            $sonCheckBox = $('.son_check');                 //每个商铺下的商品的checkbox
                        $allCheckbox.click(function () {
                            if ($(this).is(':checked')) {
                                $(this).prop("checked", true);
                            } else {
                                $(this).prop("checked", false);
                            }
                        });
                        //全局全选与单个商品的关系
                        $wholeChexbox.click(function () {
                            var $checkboxs = $cartBox.find('input[type="checkbox"]');
                            if ($(this).is(':checked')) {
                                $checkboxs.prop("checked", true);
                            } else {
                                $checkboxs.prop("checked", false);
                            }
                            totalMoney();
                        });

                        $sonCheckBox.each(function () {
                            $(this).click(function () {
                                if ($(this).is(':checked')) {
                                    //判断：所有单个商品是否勾选
                                    var len = $sonCheckBox.length;
                                    var num = 0;
                                    $sonCheckBox.each(function () {
                                        if ($(this).is(':checked')) {
                                            num++;
                                        }
                                    });
                                    if (num == len) {
                                        $wholeChexbox.prop("checked", true);
                                    }
                                } else {
                                    //单个商品取消勾选，全局全选取消勾选
                                    $wholeChexbox.prop("checked", false);
                                }
                                totalMoney();
                            })
                        });
                        $shopCheckbox.each(function () {
                            $(this).click(function () {
                                if ($(this).is(':checked')) {
                                    //判断：店铺全选中，则全局全选按钮打对勾。
                                    var len = $shopCheckbox.length;
                                    var num = 0;
                                    $shopCheckbox.each(function () {
                                        if ($(this).is(':checked')) {
                                            num++;
                                        }
                                    });
                                    if (num == len) {
                                        $wholeChexbox.prop("checked", true);
                                    }
                                    //店铺下的checkbox选中状态
                                    $(this).parents('.cartBox').find('.son_check').prop("checked", true);
                                } else {
                                    //否则，全局全选按钮取消对勾
                                    $wholeChexbox.prop("checked", false);

                                    //店铺下的checkbox选中状态
                                    $(this).parents('.cartBox').find('.son_check').prop("checked", false);
                                }
                                totalMoney();
                            });
                        });

                        //每个店铺checkbox与其下商品的checkbox的关系
                        //店铺$sonChecks有一个未选中，店铺全选按钮取消选中，若全都选中，则全选打对勾
                        $cartBox.each(function () {
                            var $this = $(this);
                            var $sonChecks = $this.find('.son_check');
                            $sonChecks.each(function () {
                                $(this).click(function () {
                                    if ($(this).is(':checked')) {
                                        //判断：如果所有的$sonChecks都选中则店铺全选打对勾！
                                        var len = $sonChecks.length;
                                        var num = 0;
                                        $sonChecks.each(function () {
                                            if ($(this).is(':checked')) {
                                                num++;
                                            }
                                        });
                                        if (num == len) {
                                            $(this).parents('.cartBox').find('.shopChoice').prop("checked", true);
                                        }
                                    } else {
                                        //否则，店铺全选取消
                                        $(this).parents('.cartBox').find('.shopChoice').prop("checked", false);
                                    }
                                    totalMoney();
                                });
                            });
                        });

                    }, 1000);
                }
                if (this.buy_car.length==0){
                    $('#buyCar_list').html(this.nodata);
                }
                /*var _this = this;
                setTimeout(function () {
                    _this.loading = false;
                }, 300);*/
                this.loading = false;
                // console.log(this.buy_car);
            }, function (res) {
            });
        }
    },
    mounted: function () {
        this.nodata += '<div class="my_no-data">';
        this.nodata += '<div class="no_data_tip">';
        this.nodata += '<img src="/image/userweb/slicesImg/no-data.png" alt="">';
        this.nodata += '<div class="no-data-text">';
        this.nodata += '<div class="title_zh">暂无数据</div>';
        this.nodata += '<div class="title_en">No data</div>';
        this.nodata += '</div>';
        this.nodata += '</div>';
        this.nodata += '</div>';
        this.user_id        = localStorage.getItem('user_id');
        this.web_token      = localStorage.getItem('web_token');
        /*if (!localStorage.getItem('buy_car') || localStorage.getItem('buy_car') == undefined || localStorage.getItem('buy_car') == '' || localStorage.getItem('buy_car') == null){
            this.buy_car        = '';
        }else{
            this.buy_car        = JSON.parse(localStorage.getItem('buy_car'));
        }*/
        if (!this.user_id ){
            location.href = "/userweb/index/login.html";
        }
        validToken(); //验证tonken.
        this.req();
    }
});
//总计
function totalMoney() {
    var $allCheckbox = $('input[type="checkbox"]'),     //全局的全部checkbox
        $wholeChexbox = $('.whole_check'),
        $cartBox = $('.cartBox'),                       //每个商铺盒子
        $shopCheckbox = $('.shopChoice'),               //每个商铺的checkbox
        $sonCheckBox = $('.son_check');
    var total_money = 0;
    var submit_order = $('.submit_order a');
    $sonCheckBox.each(function () {
        if ($(this).is(':checked')) {
            var goods = parseFloat($(this).parents('.order_col').find('.sum_price_number>span').html());
            total_money += goods;
            // console.log(goods);
        }
    });
    total_money = total_money.toFixed(2);
    $('.order_price span').html(total_money);
    //console.log(total_money);
    if(total_money!=0){
        if(!submit_order.hasClass('btn_sty')){
            submit_order.addClass('btn_sty');
        }
    }else{
        if(submit_order.hasClass('btn_sty')){
            submit_order.removeClass('btn_sty');
        }
    }
}